package com.cloud.minioService.controller;

import com.cloud.minioService.utils.MinioUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * @author zhozixiong
 * @date 2023/03/17
 */
@RestController
@RequestMapping("/minio")
public class MinioController {

    @Autowired
    private MinioUtil minioUtil;

    /**
     *  上传单张图片
     */
    @PostMapping(value = "/uploadPicture", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public String uploadPicture(@RequestPart("file") MultipartFile file, @RequestParam("bucketName") String bucketName) {
        List<String> filenameList = minioUtil.uploadFiles(bucketName, file);
        return filenameList.get(0);
    }

    /**
     *  上传多张图片
     */
    @PostMapping(value = "/uploadPictures", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public List<String> uploadPictures(@RequestPart("files") MultipartFile[] files, @RequestParam("bucketName") String bucketName) {
        List<String> filenameList = minioUtil.uploadFiles(bucketName, files);
        return filenameList;
    }

    /**
     *  下载图片
     */
    @GetMapping("/downloadPicture")
    public void downloadPicture(String bucketName, String objectName, HttpServletResponse response) throws IOException {
        InputStream in = null;
        OutputStream out = null;
        BufferedInputStream buff = null;
        try {
            response.setContentType("image/png");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + objectName);
            in = minioUtil.getObject(bucketName, objectName);
            buff = new BufferedInputStream(in);
            out = response.getOutputStream();
            IOUtils.copy(buff, out);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(out != null) {
                out.flush();
            }
            if(in != null) {
                in.close();
            }
            if(buff != null) {
                buff.close();
            }
        }
    }
}
